import { messages } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Tabs, Modal } from 'antd'
const TabPane = Tabs.TabPane;
import config from 'config'
import SearchArea from "components/search-area";
import invoiceBagApproveService from 'containers/financial-management/invoice-bag-approve/invoice-bag-approve.service'
import moment from "moment";
import menuRoute from 'routes/menuRoute'
import ReconnectingWebSocket from "reconnectingwebsocket";
import ResizeTable from 'components/resize-table'

/**
 * ╔┓┏╦━━╦┓ ╔┓ ╔━━╗
 * ║┗┛║┗━╣┃ ║┃ ║XX║
 * ║┏┓║┏━╣┗━╣┗━╣╰╯║
 * ╚┛┗╩━━╩━━╩━━╩━━╝
 */
class InvoiceBagApprove extends React.Component {
  constructor(props) {
    super(props);
    this.detailPage = menuRoute.getRouteItem('invoice-bag-approve-detail');
    this.state = {
      tabs: [
        {key: 'wait-for-approve', name: messages('financial-management.key653')/*待审批*/},
        {key: 'approved', name: messages('financial-management.key654')/*已审批*/}
      ],
      nowTab: 'wait-for-approve',
      searchForm: [
        {
          type: 'combobox',
          id: 'expenseReportBagId',
          label: messages('financial-management.key660')/*发票袋编号*/,
          options: [],
          placeholder: messages('financial-management.key761')/*请输入至少四位*/,
          searchUrl: `${config.baseUrl}/api/expense/reports/bag/fuzzy/query`,
          method: 'get',
          searchKey: 'expenseReportBagCode',
          labelKey: 'expenseReportBagCode',
          valueKey: 'id',
          getParams: { isAudit: true }
        },
        {
          type: 'rangePicker', id: 'dateRange',
          label: messages('financial-management.key479')/*提交日期*/
        },
        {
          type: 'combobox',
          id: 'userOid',
          label: messages('financial-management.key131')/*申请人*/,
          placeholder: messages('common.please.enter') + messages('financial-management.key165'/*姓名／工号*/),
          options: [],
          searchUrl: `${config.baseUrl}/api/users/v3/search?page=0&size=9999&roleType=TENANT&status=all`,
          method: 'get',
          searchKey: 'keyword',
          labelKey: 'fullName',
          valueKey: 'userOID',
          renderOption: option => (`${option.employeeID}-${option.fullName}${(option.status !== 1001 ? (
            `（${
              option.status === 1002 ? 
                messages('financial-management.key622')/*待离职员工*/ : 
                messages('financial-management.key623')/*离职员工*/
            }）`
          ) : '')}`)
        }
      ],
      columns: [{
        dataIndex: 'index', title: messages('financial-management.key403')/*序号*/, width: '10%'
      }, {
        dataIndex: 'fullName', title: messages('financial-management.key131')/*申请人*/, width: '20%'
      }, {
        dataIndex: 'employeeId', title: messages('financial-management.key130')/*工号*/, width: '10%'
      }, {
        dataIndex: 'lastSubmittedDate', title: messages('financial-management.key479')/*提交日期*/, width: '20%',
        render: date => moment(date).local().format('YYYY-MM-DD')
      }, {
        dataIndex: 'expenseReportBagCode', title: messages('financial-management.key660')/*发票袋编号*/, width: '40%'
      }],
      data: [],
      pagination: {
        total: 0,
      },
      page: 0,
      size: 10,
      searchParams: {},
      loading: false,
      count: {
        auditBagNumber: 0,
        passBagNumber: 0
      },
      loadingCount: false,
      hasConfirm: false
    };
    this.data = [];
  }

  componentWillMount() {
    if(this.connector)
      this.connector.close();
    !window.ISIE9 && this.openWebSocket();
  }

  componentWillUnmount = () => {
    if(this.connector)
      this.connector.close();
  };

  //webSocket扫码审核开始
  openWebSocket = () => {
    let url = `${config.wsUrl}/ws/scancode?scanMode=BAG_REVIEW`;
    this.connector = new ReconnectingWebSocket(url);
    this.connector.onopen = this.onOpen;
    this.connector.onerror = this.onError;
    this.connector.onmessage = this.onMessage;
    this.connector.onclose = this.onClose;
  };

  onOpen = () => {
    let body = {
      userOID: this.props.user.userOID,
      token: this.props.authToken.access_token
    };
    let dict = {
      command: 'AUTH',
      body: JSON.stringify(body)
    };
    let dataSend = JSON.stringify(dict) + '\0';
    this.connector.send(dataSend);
  };

  onError = () => {
    this.setState({ connectStatus: false })
  };

  onMessage = (message) => {
    this.data.push(JSON.parse(JSON.stringify(message)).data);
    this.analyseData();
  };

  onClose = () => {
    if (this.state.connectStatus)
      this.setState({connectStatus: false});
  };

  analyseData = () => {
    let lastReceive = this.data.pop();
    let end = '\0';
    if (lastReceive.indexOf(end) === -1) {
      this.data.push(lastReceive);
      return;
    }
    let temp = lastReceive.split(end);
    let data = JSON.parse(this.data.join('') + temp[0]);
    if (temp[1] !== '') {
      this.data = [];
      this.data.push(temp[1]);
    }
    if (data.command === 'ERROR') {
      if (this.state.hasConfirm)
        return;
      this.setState({hasConfirm: true});
      Modal.confirm({
        title: 'Oops',
        content: data.body,
        okText: messages('financial-management.key202'/*重连*/),
        cancelText: messages('common.cancel')/*取消*/,
        onOk: () => {
          this.setState({hasConfirm: false});
        },
        onCancel: () => {
          this.setState({hasConfirm: false});
          this.data = [];
          this.connector.close();
        }
      })
    }
    data.body = JSON.parse(data.body);
    if (!data.body || !data.body.type || !data.body.content) return;
    if (data.command !== 'MESSAGE') return;
    let content = data.body.content.split(':');
    if (data.body.type === 'AUTH_SUCCESS') {
      this.setState({ connectStatus: true });
    } else if(data.body.type === 'BAG_REVIEW') {
      this.context.router.push(this.detailPage.url.replace(':id', content[0]) + `?tab=wait-for-approve`);
    }
  };

  componentDidMount(){
    this.setState({ nowTab: this.props.location.query.tab || 'wait-for-approve' ,loadingCount: true }, () => {
      invoiceBagApproveService.getBagCount()
        .then(res => {
          this.setState({ count: res.data });
          this.getList();
        })
        .finally(() => {
          this.setState({ loadingCount: false });
        });
    });
  }

  getList = () => {
    const { page, size, searchParams, nowTab } = this.state;
    this.setState({ loading: true });
    invoiceBagApproveService.getBagList(page, size, {...searchParams, isAudit: nowTab === 'wait-for-approve'})
      .then(res => {
        this.setState({
          data: res.data.map((item, index) => { item.index = index + 1 + page * size; return item }),
          loading: false,
          pagination: {
            total: Number(res.headers['x-total-count']) || 0,
            onChange: this.onChangePager,
            current: page + 1
          }
        })
    }).catch(() => {
        this.setState({ loading: false });
      })
  };

  onChangePager = page => {
    if(page - 1 !== this.state.page)
      this.setState({ page: page - 1 },  this.getList)
  };

  handleSearch = searchParams => {
    if(searchParams.dateRange && searchParams.dateRange.length > 0) {
      searchParams.dateFrom = searchParams.dateRange[0].format('YYYY-MM-DD+00:00:00');
      searchParams.dateTo = searchParams.dateRange[1].format('YYYY-MM-DD+23:59:59');
    }
    delete searchParams.dateRange;
    if(searchParams.dateRange) {

    }
    this.setState({ searchParams }, this.getList)
  };

  handleClear = () => {
    this.setState({ searchParams: {} }, this.getList)
  };

  handleChangeTab = key => {
    const { searchForm } = this.state;
    searchForm[0].getParams = { isAudit: key === 'wait-for-approve' };
    this.setState({ nowTab: key, searchForm, page: 0 }, () => this.formRef.handleReset());
  };

  handleRowClick = record => {
    const { nowTab } = this.state;
    this.context.router.push(this.detailPage.url.replace(':id', record.id) + `?tab=${nowTab}`);
  };

  render() {
    const { tabs, count, searchForm, columns, data, loading, pagination, loadingCount, nowTab } = this.state;
    return (
      <div>
        <div className="tabs-info">
          <Tabs onChange={this.handleChangeTab} type="card" activeKey={nowTab}>
            {tabs.map(tab => (
              <TabPane key={tab.key} tab={
                <span>
                  {tab.name}
                  ({loadingCount ? '-' :
                    count[tab.key === 'wait-for-approve' ? 'auditBagNumber' : 'passBagNumber']})
                </span>
              }/>
              ))}
          </Tabs>
        </div>
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.handleSearch}
          clearHandle={this.handleClear}
          wrappedComponentRef={inst => this.formRef = inst}
        />
        <div className="table-header">
          <div className="table-header-title">
            {messages('common.total',{ total: `${pagination.total}` })}
          </div>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          bordered
          size="middle"
          pagination={pagination}
          loading={loading}
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
        />
      </div>
    )
  }
}

InvoiceBagApprove.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    authToken: state.main.authToken
  }
}

export default connect(mapStateToProps)(InvoiceBagApprove)
